package com.fht.spring_boot_study.model.account.service.impl;

import com.fht.spring_boot_study.model.account.entity.User;
import com.fht.spring_boot_study.model.account.repository.AccountRepository;
import com.fht.spring_boot_study.model.account.service.AccountService;
import com.fht.spring_boot_study.model.common.entity.ResultEntity;
import com.fht.spring_boot_study.model.common.entity.SearchBean;
import com.fht.spring_boot_study.model.test.entity.Student;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountRepository accountRepository;
    @Override
    @Transactional
    public ResultEntity<User> insertUser(User user) {
        accountRepository.saveAndFlush(user);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Insert success.", user);
    }

    @Override
    @Transactional
    public ResultEntity<User> updatetUser(User user) {
       accountRepository.saveAndFlush(user);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Update success.", user);
    }

    @Override
    public ResultEntity<User> deleteUser(int id) {
       accountRepository.deleteById(id);
        return new ResultEntity<>(ResultEntity.ResultStatus.SUCCESS.code,
                "Delete success.");
    }

    @Override
    public Page<User> getUsersBySearchBean(SearchBean searchBean) {
        return exampleAndPage(searchBean);
    }
    public Page<User> exampleAndPage(SearchBean searchBean) {
        searchBean.initSearchBean();
        Sort.Direction direction = StringUtils.isBlank(searchBean.getDirection()) ||
                searchBean.getDirection().equalsIgnoreCase("asc") ?
                Sort.Direction.ASC : Sort.Direction.DESC;
        String orderBy = StringUtils.isBlank(searchBean.getOrderBy()) ?
                "id" : searchBean.getOrderBy();
        Sort sort = Sort.by(direction, orderBy);
        PageRequest pageRequest = PageRequest.of(searchBean.getCurrentPage() - 1,
                searchBean.getPageSize(), sort);

        User user = new User();
        user.setUserName(searchBean.getKeyWord());
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("userName", matcher -> matcher.contains());
        Example<User> example = Example.of(user, exampleMatcher);

        return accountRepository.findAll(example,pageRequest);
    }
}
